﻿using System;

namespace LuaNet
{
	/// <summary>
	/// Description of StateExtensions.
	/// </summary>
	public class StateExtensions
	{
      	public static bool TryToNumber(LuaState state, int index, out Double result)
        {
            bool res;
            result = state.ToNumber(index, out res);
            return res;
        }

        public static bool TryToInteger(LuaState state, int index, out Int32 result)
        {
            bool res;
            result = state.ToInteger(index, out res);
            return res;
        }

        public static String ToLString(LuaState state, int index, out int len)
        {
            var s = state.ToString(index);
            len = s.Length;
            return s;
        }

        public static LuaStatus LoadBuffer(LuaState state, String s, String n) 
        { 
        	return state.LoadBuffer(s, s.Length, n); 
        }

        public static String PushLString(LuaState state, String s, int len)
        {
            s = s.Substring(0, len);
            state.PushString(s);
            return s;
        }

        public static T ToUserData<T>(LuaState state, int index)
        {
            var o = state.ToUserData(index);
            return o is T ? (T)o : default(T);
        }

        public static int Ref(LuaState state)
        {
            return state.LRef(state.RegistryIndex);
        }

        public static LuaType GetRef(LuaState state, int reference)
        {
            return state.RawGetI(state.RegistryIndex, reference);
        }

        public static LuaState Unref(LuaState state, int reference)
        {
            state.LUnref(state.RegistryIndex, reference);
            return state;
        }
	}
}
